import request from '@/utils/request'
//后台位置更新时自动触发
export default {
	sendLocaltionAuto(group_id){
		function uploadLivePosition() {
			uni.onLocationChange(async (res) => {
				//当位置出现变化时自动发送
				//通过 WebSocket 连接发送数据
				let user = JSON.parse(uni.getStorageSync("user"))
	
				let client_id = uni.getStorageSync("client_id")
				const message = {
					group_id: group_id,
					id: user.id,
					username: user.name,
					usericon: user.avatar,
					latitude: res.latitude,
					longitude: res.longitude,
				}
	
				await request.post("chat/broadcastUsersLocation",
					message)
			});
		}
	
		uni.authorize({
			scope: 'scope.userLocationBackground',
			success: () => {
				// console.log("后台接受位置消息成功")
				uni.startLocationUpdateBackground({
					success: res => {
						// console.log('开启小程序接收位置消息成功')
						uploadLivePosition()
					},
					fail: err => console.error('开启小程序接收位置消息失败：', err),
					complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
				});
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: "您可以点击右上角小点开启实时定位",
					duration: 2500
				})
				uni.startLocationUpdate({
					success: res => {
						console.log('开启小程序接收位置消息成功')
						uploadLivePosition()
					},
					fail: err => console.error('开启小程序接收位置消息失败：', err),
					complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
				});
			}
		})
	
	}
	
}